<!DOCTYPE html>
<html lang="ko">
  <head>
  
	<!--[if lt IE 9]>
	<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	
	<!--[if lt IE 9]>
	<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
	<![endif]-->
	
	<!--[if lt IE 8]>
	<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>
	<![endif]-->
	
	<!--[if lt IE 7]>
	<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE7.js"></script>
	<![endif]-->
	
	<script>
	document.createElement('header');
	document.createElement('nav');
	document.createElement('article');
	document.createElement('section');
	document.createElement('aside');
	document.createElement('footer');
	</script>
	
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap-ko.min.css"/>
    <link rel="stylesheet" href="lib/font-awesome/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="lib/ol3/css/ol.css" type="text/css"/>
    
    <style>
    .modal {
    	overflow-y: auto;
	}
	/* custom class to override .modal-open */
	.modal-noscrollbar {
	    margin-right: 0 !important;
	}
	@-webkit-viewport{width:device-width}
	@-moz-viewport{width:device-width}
	@-ms-viewport{width:device-width}
	@-o-viewport{width:device-width}
	@viewport{width:device-width}

      html, body, #map {
        height: 100%;
        width: 100%;
        overflow: hidden;
      }
      body {
        padding-top: 50px;
      }
      .navbar .navbar-brand {
        font-weight: bold;
        font-size: 25px;
        color: white;
      }
      .nopadding {
         padding: 0 !important;
         margin: 0 !important;
      }
      .drawcursor {
        cursor: crosshair !important;
      }
      #draw-btn.active {
        color: #00FF00 !important;
      }
      #header { min-width: 1000px; }
    </style>
    
    <script type="text/javascript">
    if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
        var msViewportStyle = document.createElement("style");
        msViewportStyle.appendChild(
            document.createTextNode(
                "@-ms-viewport{width:auto!important}"
            )
        );
        document.getElementsByTagName("head")[0].
            appendChild(msViewportStyle);
    }
    </script>
    
    <title>Test Map</title>
  </head>
  <body>
  <!-- 
	<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
		<div class="container">
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collpased"
					data-toggle="collapse" data-target=".navbar-collapse">
					<span class="sr-only">Toggle navigation</span> <span
						class="icon-bar"></span> <span class="icon-bar"></span> <span
						class="icon-bar"></span>
				</button>
				<a class="navbar-brand" href="#">Test</a>
			</div>

			<div class="collapse navbar-collapse">
				<ul class="nav navbar-nav">
					<li class="active"><a href="#">Home</a></li>
					<li><a href="#about">About</a></li>
					<li><a href="#contact">Contact</a></li>
				</ul>
			</div>
		</div>
	</div>
-->
<!-- 
	<div class="container">
		<div id="map"></div>
	</div>
 -->
 
 <!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <div id="modalInfo" >
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <!-- <button type="button" class="btn btn-primary">Save changes</button> -->
      </div>
    </div>
  </div>
</div>

    <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <!-- <p class="navbar-brand">TTTTTTTTTT</p> -->
        <a class="navbar-brand" href="#">테스트 지도</a>
      </div>
      <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li><a href="#" data-toggle="collapse" data-target=".navbar-collapse.in" onclick="zoomToExtent(); return false;"><i class="fa fa-arrows-alt"></i>&nbsp;&nbsp;Zoom To Full Extent</a></li>
          <li><a href="#" id="draw-btn" class="" data-toggle="collapse" data-target=".navbar-collapse.in" onclick="geolocation.setTracking(true); return false;"><i class="fa fa-edit"></i>&nbsp;&nbsp;Draw Feature</a></li>
          <li><a href="#" data-toggle="collapse" data-target=".navbar-collapse.in" onclick="deleteFeature(); return false;"><i class="fa fa-trash-o"></i>&nbsp;&nbsp;Delete Feature</a></li>
        </ul>
      </div>
    </div>
    
    <div id="map" class="map"></div>

	
    <script src="lib/jquery/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script src="lib/ol3/ol.js" type="text/javascript"></script>
    <script src="baseMap.js" type="text/javascript"></script>
    <script src="lib/bootstrap/js/bootstrap.min.js"></script>
    
    <script src="lib/proj4js/proj4.js" type="text/javascript"></script>
	<script src="proj4EpsgKorea.js" type="text/javascript"></script>
    
	<script type="text/javascript">
	
    //var maxZoom = resolutions.length - 1;

    //var baseMap = new ol.layer.vworldMap('hybrid');
    var baseMap = new ol.layer.vworldMap('street');
    //var baseMap2 = new ol.layer.vworldMap('satellite');

	var projection = baseMap.getProjection();

    var wmsSeoulSource = new ol.source.TileWMS({			//ImageWMS
        url: '/geoserver/wms',
        params: {
            'LAYERS': 'seoul:admin_emd',
            //'LAYERS': 'daegu:admin_emd',
            'STYLES': '',
            'VERSION': '1.1.1',
            'SRS': projection.getCode(),
            'TRANSPARENT': true,
            'TILED': true
            },
        serverType: 'geoserver'
    });

    var wmsSeoulLayer = new ol.layer.Tile({
    	extent: baseMap.getExtent(),
        source: wmsSeoulSource,
        projection: projection
    });

    var select = new ol.interaction.Select();

    var modify = new ol.interaction.Modify({
      features: select.getFeatures()
    });

    var baseMapExtent = baseMap.getExtent();
    var map = new ol.Map({
    	interactions: ol.interaction.defaults().extend([select, modify]),
        controls: ol.control.defaults({
            attributionOptions: ({
                collapsible: false
            })
        }),    
        target: 'map',
        layers: [],
        renderer: 'canvas',

        view: new ol.View({
            projection: projection,

            maxResolution: baseMap.getMaxResolution(),
            //minResolution: baseMap.getMinResolution(),
            maxZoom: baseMap.getMaxZoom(),
            //minZoom: baseMap.getMinZoom(),
            maxExtent: baseMapExtent,
            zoomFactor: 2,
            center: baseMap.getInitCenter(),
            zoom: baseMap.getInitZoom()
        })
    });

    var vectorSeoulEmdSource = new ol.source.ServerVector({
		format: new ol.format.GeoJSON(),
		loader: function(extent, resolution, projection) {
			var url = 	'/geoserver/wfs?service=WFS&' +
						'version=1.1.0&request=GetFeature&typename=seoul:admin_emd&' +
						'outputFormat=text/javascript&format_options=callback:loadSeoulEmdFeatures' +
						'&srsname='+projection.getCode()+'&bbox=' + extent.join(',') + ','+projection.getCode();
    	    $.ajax({
    	      url: url,
    	      dataType: 'jsonp'
    	    });
		},
		strategy: ol.loadingstrategy.createTile(new ol.tilegrid.XYZ({maxZoom: 19})),
		projection: projection.getCode()
	});

    var vectorRiverSource = new ol.source.ServerVector({
		format: new ol.format.GeoJSON(),
		loader: function(extent, resolution, projection) {
			var url = 	'/geoserver/wfs?service=WFS&' +
						'version=1.1.0&request=GetFeature&typename=seoul:river&' +
						'outputFormat=text/javascript&format_options=callback:loadRiverFeatures' +
						'&srsname='+projection.getCode()+'&bbox=' + extent.join(',') + ','+projection.getCode();
    	    $.ajax({
    	      url: url,
    	      dataType: 'jsonp'
    	    });
		},
		strategy: ol.loadingstrategy.createTile(new ol.tilegrid.XYZ({maxZoom: 19})),
		projection: projection.getCode()
	});

    var vectorFireStationSource = new ol.source.ServerVector({
		format: new ol.format.GeoJSON(),
		loader: function(extent, resolution, projection) {
			var url = 	'/geoserver/wfs?service=WFS&' +
						'version=1.1.0&request=GetFeature&typename=seoul:firestation&' +
						'outputFormat=text/javascript&format_options=callback:loadFireStationFeatures' +
						'&srsname='+projection.getCode()+'&bbox=' + extent.join(',') + ','+projection.getCode();
    	    $.ajax({
    	      url: url,
    	      dataType: 'jsonp'
    	    });
		},
		strategy: ol.loadingstrategy.createTile(new ol.tilegrid.XYZ({maxZoom: 19})),
		projection: projection.getCode()
	});

	var loadSeoulEmdFeatures = function(response) {
		vectorSeoulEmdSource.addFeatures(vectorSeoulEmdSource.readFeatures(response));

	    //map.getView().fitExtent(vectorRiverSource.getExtent(), map.getSize());
	};

	var loadRiverFeatures = function(response) {
		vectorRiverSource.addFeatures(vectorRiverSource.readFeatures(response));

	    //map.getView().fitExtent(vectorRiverSource.getExtent(), map.getSize());
	};
	var loadFireStationFeatures = function(response) {
		vectorFireStationSource.addFeatures(vectorFireStationSource.readFeatures(response));

	    //map.getView().fitExtent(vectorRiverSource.getExtent(), map.getSize());
	};

	var vectorSeoulEmdLayer = new ol.layer.Vector({
		source: vectorSeoulEmdSource,
	});

 	var vectorRiverLayer = new ol.layer.Vector({
		source: vectorRiverSource,
		style: new ol.style.Style({
			stroke: new ol.style.Stroke({
				color: 'rgba(255, 0, 0, 0.5)',
				width: 2
			}),
			fill: new ol.style.Fill({color: 'rgba(255, 0, 0, 0.5)'})
		})
 	});

 	var vectorFireStationLayer = new ol.layer.Vector({
		source: vectorFireStationSource/*,
		style: new ol.style.Circle({
			stroke: new ol.style.Stroke({
				color: 'rgba(255, 0, 0, 0.5)',
				width: 2
			}),
			radius: 3,
			fill: new ol.style.Fill({color: 'rgba(255, 0, 0, 0.5)'})
		})*/
 	});

 	function zoomToExtent() {
 		map.getView().fitExtent(vectorRiverSource.getExtent(), map.getSize());
 	};

 	var serializer_ = new XMLSerializer();
 	var format_ = new ol.format.WFS();

 	function deleteFeature() {
 	 	if (selectedFeature) {
			var a = selectedFeature;
 	 		(a = this.format_.writeTransaction(null, null, [selectedFeature], {
 	 	        featureNS: "http://www.geoserver.org/seoul",
 	 	        featureType: "firestation",
 	 			}), $.ajax({
 	 	        type: "POST",
 	 	        url: "/geoserver/wfs?",
 	 	        beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa("admin" + ":" + "geoserver")); },
 	 	        data: this.serializer_.serializeToString(a),
 	 	        contentType: "text/xml",
 	 	        success: function(a) {
 	 	        	var summary = this.format_.readTransactionResponse(a).transactionSummary;
 	 	        	if (summary) {
	 	 	 	        if (summary.totalDeleted) {
	 	 	 	        	alert( "delete ok!" );
	 	 	 	        	select.getFeatures().clear();
	 	 	 	        	vectorFireStationSource.removeFeature(selectedFeature);
	 	 	 	        	selectedFeature = null;
	 	 	 	 	    }
	 	 	 	        else {
							alert( "failure" );
	 	 	 	 	    }
 	 	        	}
 	 	        	else {
 	 	        		alert( new XMLSerializer().serializeToString(a) );
 	 	 	        }
 	 	        },
 	 	        context: this
 	 	}));
 	 	 	
 	 	}
 	}

    //map.addLayer(baseMap2);
    map.addLayer(baseMap);
    map.addLayer(wmsSeoulLayer);
    //map.addLayer(vectorSeoulEmdLayer);
    map.addLayer(vectorRiverLayer);
    map.addLayer(vectorFireStationLayer);
    
	var geolocation = new ol.Geolocation( ({
		trackingOptions: {
			maximumAge: 10000,
			enableHighAccuracy: true,
			timeout: 600000
		}
		}) 
	);

	geolocation.bindTo('projection', map.getView());
	geolocation.setProjection(map.getView().getProjection());

	var geoProjection = geolocation.getProjection();
	
	var deltaMean = 500; // the geolocation sampling period mean in ms

	// Listen to position changes
	geolocation.on('change:position', function(evt) {
	  var position = geolocation.getPosition();

	  geolocation.setTracking(false);

	  map.getView().setCenter(position);
	  map.getView().setZoom(10);
	});

	geolocation.on('error', function() {
		geolocation.setTracking(false);
		alert('geolocation error');
	});

	geolocation.setTracking(true);

	var accuracyFeature = new ol.Feature();
	accuracyFeature.bindTo('geometry', geolocation, 'accuracyGeometry');

	var positionFeature = new ol.Feature();
	positionFeature.bindTo('geometry', geolocation, 'position')
	    .transform(function() {}, function(coordinates) {
	      return coordinates ? new ol.geom.Point(coordinates) : null;
	    });

	var featuresOverlayGeolocation = new ol.FeatureOverlay({
	  map: map,
	  features: [accuracyFeature, positionFeature]
	});

	//var editFeature = new ol.Feature();
	var editFeatureOverlay = new ol.FeatureOverlay({
		map: map,
		features: [],
		style: new ol.style.Style({
	 	    stroke: new ol.style.Stroke({
				color: '#0f0',
				width: 3
	 	    }),
	 	    fill: new ol.style.Fill({
				color: 'rgba(0,255,0,0.5)'
	 	    })
		})
	});

    var featureOverlay = new ol.FeatureOverlay({
		map: map,
		style: new ol.style.Style({
	 	    stroke: new ol.style.Stroke({
				color: '#0f0',
				width: 3
	 	    }),
	 	    fill: new ol.style.Fill({
				color: 'rgba(0,255,0,0.5)'
	 	    })
		})
	});

    var highlight;
    var selectedFeature = null;
    var displayFeatureInfo = function(pixel) {

		var feature = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
			return feature;
		});

		if (feature !== highlight) {
			if (highlight) {
				featureOverlay.removeFeature(highlight);
			}
			if (feature) {
				featureOverlay.addFeature(feature);
			}
			highlight = feature;
		}

	};
    var displayFeatureInfo2 = function(pixel) {

		var feature = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
			return feature;
		});

		if (feature) {
			selectedFeature = feature;
			var html = "id: " + feature.getId();
			//for (var key in feature.getKeys() )
			for (var i=0; i<feature.getKeys().length; i++) {
				var value = feature.get(feature.getKeys()[i]);
				if (value instanceof ol.geom.Geometry) {
					html = html + '<br>' + feature.getKeys()[i] + ": " + value.getType();
					continue;
				}
				html = html + '<br>' + feature.getKeys()[i] + ": " + value;
			}
			$('#myModalLabel').html('test1234');
			$('#modalInfo').html(html);//.innerHTML = 'blah blah';
		}
		else {
			selectedFeature = null;
		}

		/*
		var info = document.getElementById('info');
		if (feature) {
			info.innerHTML = feature.getId() + ': ' + feature.get('name');
		} else {
			info.innerHTML = '&nbsp;';
		}
		*/
		if (feature) {
			$('#myModal').modal('show'); return false;
		}

		if (feature == highlight) {
			if (highlight) {
				featureOverlay.removeFeature(highlight);
			}
			highlight = null;
		}

	};

	$(map.getViewport()).on('mousemove', function(evt) {
		var pixel = map.getEventPixel(evt.originalEvent);
		displayFeatureInfo(pixel);
	});

	$(map.getViewport()).on('mousedown', function(evt) {
		$(map.getViewport()).on('mouseup mousemove', function handler(evt) {
			if (evt.type == 'mouseup') { // click
				var pixel = map.getEventPixel(evt.originalEvent);
				displayFeatureInfo2(pixel);
			} else {
				// drag
			}
			$(map.getViewport()).off('mouseup mousemove', handler);
		});
	});

	/*$(map.getViewport()).on('click', function(evt) {
		var pixel = map.getEventPixel(evt.originalEvent);
		displayFeatureInfo2(pixel);
	})*/

	var formatJson = new ol.format.GeoJSON();
	map.on('singleclick', function(evt) {
		  var viewResolution = (map.getView().getResolution());
		  var url = wmsSeoulSource.getGetFeatureInfoUrl(
		      evt.coordinate, viewResolution, map.getView().getProjection().getCode()/*'EPSG:3857'*/,
		      {'INFO_FORMAT': 'application/json'});
		  if (url) {
			  $.ajax({
	 	 	        type: "GET",
	 	 	        url: url,
	 	 	        dataType: 'json',
	 	 	        success: function(response) {
		 	 	        var featureCollection = editFeatureOverlay.getFeatures();
		 	 	      	featureCollection.clear();
		 	 	        var features = formatJson.readFeatures(
				 	 	        response, {featureProjection: map.getView().getProjection().getCode()});
						
		 	 	        for ( var i in features ) {
			 	 	        //features[i].getGeometry().transform( 'EPSG:5174', map.getView().getProjection().getCode() );
	 	 	        		editFeatureOverlay.addFeature( features[i] );
		 	 	        }
		 	 	        /*
		 	 	        if (features[0])
			 	 	    {
				 	 	    var extent = features[0].getGeometry().getExtent();
				 	 	    map.getView().fitExtent(extent, map.getSize());
			 	 	    }
			 	 	    */
	 	 	        }
			  });
		  }
		});

    </script>
  </body>
</html>
